﻿using Shop.Product.Entity;
using Shop.Product.Interface;
using Shop.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Shop.Entity;
using Shop.Tools;
using Shop.Product.Entity.Insert;
using Shop.Product.Entity.Update;

namespace Shop.Product.Server
{
    public class ProductBaseType : BaseServer<ProductBaseTypePo>, IProductBaseType
    {
        public List<ProductBaseTypePo> GetPage(string typeName, int isDel, int isShow, int parentId, int pageIndex, int pageSize, out int total)
        {
            total = 0;
            return db.Queryable<ProductBaseTypePo>().WhereIF(!typeName.IsNullOrEmpty(), $" ( TpyeCn like @typeName  or TpyeEn like @typeName or TpyeCh like @typeName)", new { typeName = $"%{typeName}%" })
                .WhereIF(isDel > -1, $" isDel = @isDel ", new { isDel = isDel == 1 })
                .WhereIF(isShow > -1, $" isShow = @isShow ", new { isShow = isShow == 1 })
                .WhereIF(parentId > -1, $" parentId = @parentId ", new { parentId = parentId })
                .ToPageList(pageIndex, pageSize, ref total);
        }

        public  bool Insert(AddProductBaseType t, ComUser com)
        {
            t.CreateId = com.Id;
            t.CreateName = com.UserName;
            var model = db.Queryable<ProductBaseTypePo>().Where(x => x.IsDel == false && x.Sort == t.Sort).First();
            if (t.Sort == 0 || model?.Id > 0)
            {
                var maxSort = db.Queryable<ProductBaseTypePo>().Where(x => x.IsDel == false).Max(x => x.Sort);
                t.Sort = maxSort + 1;
            }
            return db.Insertable(t).ExecuteCommand() > 0;
        }

        public  bool Update(UpdateProductBaseType t, ComUser com)
        {
            t.UpdateAt = DateTime.Now;
            t.UpdateId = com.Id;
            t.UpdateName = com.UserName;
            var model=db.Queryable<ProductBaseTypePo>().Where(x => x.IsDel == false && x.Sort == t.Sort&&x.Id!=t.Id).First();
            if (t.Sort == 0 || model?.Id > 0)
            {
                var maxSort = db.Queryable<ProductBaseTypePo>().Where(x => x.IsDel == false).Max(x => x.Sort);
                t.Sort = maxSort + 1;
            }
            return db.Updateable(t).ExecuteCommand() > 0;
        }
    }
}
